﻿/// <reference path="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js" />
//#region juery 扩展
window.ldid = 0;
$.extend({
    //生成一个唯一的id
    uniqueId: function() {
        return "ld-ui-" + (++window.ldid);
    },
    isN: function(o) { return typeof o == "number"; },
    isInt: function(o) { return $.isN(o) && Math.round(o) == o; },
    round: function(n, mantissa) {
        if (!mantissa) mantissa = 0;
        if (mantissa <= 0) return Math.round(n);
        var v = 1;
        for (var i = 0; i < mantissa; i++) v *= 10;
        return Math.round(n * v) / v;
    },
    formatMoney: function(num, n) {
        num = String(num.toFixed(n ? n : 2));
        var re = /(-?\d+)(\d{3})/;
        while (re.test(num)) num = num.replace(re, "$1,$2");
        return n ? num : num.replace(/^([0-9,]+\.[1-9])0$/, "$1").replace(/^([0-9,]+)\.00$/, "$1");;
    },
    formatMoneyToDeciamil: function(moneyStr) {
        return parseFloat(moneyStr.replace(",", ""));

    },
    lajax: function(obj) {
        var url, params, callback, errorHandler, type, async, dataType;
        url = obj.url;
        params = obj.params;
        callback = obj.callback;
        errorHandler = obj.errorHandler;
        type = obj.type;
        async = obj.async;
        dataType = obj.dataType;

        if (!url) throw new Error("url is undefined");
        type = type || "POST";
        async = async || true;
        dataType = dataType || "json";
        $.ajax({
            type: type,
            async: async,
            data: params,
            dataType: dataType,
            url: url,
            //contentType: "application/json;charset=utf-8",
            beforeSend: function(XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("isajax", "true");
                //$(".return_confrim").html("<img src='jquery/images/loading.gif'/>&nbsp;&nbsp;&nbsp;&nbsp;正在验证账户...");
            },
            success: function(d) {
                callback && callback(d);
            },
            error: function(e) {
                if (errorHandler) {
                    errorHandler(e);
                } else {
                    if (!e.responseText) {
                        $.loadend();
                        return;
                    }

                    if (JSON.parse(e.responseText).errorMessage) {
                        $.jAlert(JSON.parse(e.responseText).errorMessage);
                    } else {
                        $.jAlert(e.responseText);
                    }
                    $.loadend();
                }
            }
        });
    },
    submitForm: function(url, obj, options) {
        ///<summary>表单提交</summary>
        ///<param name=""></param>
        var defalut = { url: url, method: "post", target: "_self" };
        $.extend(true, defalut, options);
        var form = $("<form/>").attr("method", defalut.method).attr("action", defalut.url).attr("target", defalut.target).attr("autocomplete", "off").attr("onsubmit", "javascript:return true");
        $(document.body).append(form);
        for (var x in obj) {
            var input = $('<input type="hidden"/>').attr("name", x).val(obj[x]);
            form.append(input);
        }
        form.submit();
        //form.remove();
    },
    lalert: function(message) {
        alert(message);
    },
    lconfirm: function (message,callback) {
        if (confirm(message)) {
            callback();
        } else {
            return;
        }
    },
    loading:function(){
    },
    loadend:function(){
    },
    stopPropagation: function(ev) {
        if (ev.stopPropagation) {
            ev.stopPropagation();
        }
        else if (window.event) {
            window.event.cancelBubble = true;//兼容IE
        }
    }
});
//#endregion

//#region 弹出框
$.extend({
    LWindow: function (obj) {
        var title, id, url, content, classes, width, callback;
        title = obj.title;
        id = obj.id;
        url = obj.url;
        content = obj.content;
        classes = obj.classes || "";
        width = obj.width;
        height = obj.height;
        callback = obj.callback;
        var $id = $("#" + id);
        if ($id.size() > 0) {
            return;
        }
        var html = [];
        html.push('<div class="ld-window ' + classes + '" id="' + id + '" style="' + (width ? "width:" + width + "px;" : "") + (height ? "height:" + height + "px" : "")+'">');
        html.push('<dl>');
        html.push('<dt>' + title + '<span id="ld-window-close"></span></dt>');
        html.push('<dd>');
        if (url) {
            html.push('<iframe frameborder="no" border="0" width="100%" height="100%" src="' + url + '"></iframe>');
        } else if (content) {
            html.push(content);
        } else {

        }
        html.push('</dd>');
        html.push('</dl>');
        html.push('</div>');
        $("body").append('<div class="ld-mask-bg"></div>');
        $("body").append(html.join(""));


        $id = $("#" + id);

        $("#" + id).find("dt>span#ld-window-close").bind("click", function () {
            $(".ld-mask-bg").remove();
            $("#" + id).remove();
        });

        $(window).resize(function () {
            $id.css({
                left: ($(window).width() - $id.outerWidth()) / 2,
                top: ($(window).height() - $id.outerHeight()) / 2 + $(document).scrollTop()
            });
        });

        $(window).resize();

        $(window).scroll(function () {
            $id.css({
                left: ($(window).width() - $id.outerWidth()) / 2,
                top: ($(window).height() - $id.outerHeight()) / 2 + $(document).scrollTop()
            });
        });

        if (callback) {
            callback();
        }
        return $id;
    }
});

$.fn.CloseWindow = function () {
    $(this).parents("body").find(".ld-mask-bg").remove();
    $(this).remove();
};
//#endregion

//#region json
if (!this.JSON) { this.JSON = {}; }
(function () {
    function f(n) { return n < 10 ? '0' + n : n; }
    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function (key) {
            return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
        }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); };
    }
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }
    function str(key, holder) {
        var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); }
        if (typeof rep === 'function') { value = rep.call(holder, key, value); }
        switch (typeof value) {
            case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; }
                gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') {
                    length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; }
                    v = partial.length === 0 ? '[]' : gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v;
                }
                if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } }
                v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v;
        }
    }
    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {
            var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; }
            rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); }
            return str('', { '': value });
        };
    }
    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {
            var j; function walk(holder, key) {
                var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } }
                return reviver.call(holder, key, value);
            }
            cx.lastIndex = 0; if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; }
            throw new SyntaxError('JSON.parse');
        };
    }
}());

if (this.JSON && !this.JSON.parseWithDate) {
    var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
    var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
    // original var reMsAjax = /^\/Date\((d|-|.*)\)\/$/;

    JSON.parseWithDate = function (json) {
        /// <summary>
        /// parses a JSON string and turns ISO or MSAJAX date strings
        /// into native JS date objects
        /// </summary>
        /// <param name="json" type="var">json with dates to parse</param>
        /// </param>
        /// <returns type="value, array or object" />
        try {
            var res = JSON.parse(json,
            function (key, value) {
                if (typeof value === 'string') {
                    var a = reISO.exec(value);
                    if (a) {
                        if (a.length > 6) {
                            return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
                        }
                        else {
                            return null;
                        }
                    }
                    a = reMsAjax.exec(value);
                    if (a) {
                        if (a.length > 0) {
                            var b = a[1].split(/[-+,.]/);
                            return new Date(b[0] ? +b[0] : 0 - +b[1]);
                        }
                        else {
                            return null;
                        }
                    }
                }
                return value;
            });
            return res;
        }
        catch (e) {
            // orignal error thrown has no error message so rethrow with message
            throw new Error("JSON content could not be parsed");
            return null;
        }
    };
    JSON.stringifyWcf = function (json) {
        /// <summary>
        /// Wcf specific stringify that encodes dates in the
        /// a WCF compatible format ("/Date(9991231231)/")
        /// Note: this format works ONLY with WCF.
        ///       ASMX can use ISO dates as of .NET 3.5 SP1
        /// </summary>
        /// <param name="key" type="var">property name</param>
        /// <param name="value" type="var">value of the property</param>
        return JSON.stringify(json, function (key, value) {
            if (typeof value == "string") {
                var a = reISO.exec(value);
                if (a) {
                    var val = '/Date(' + new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])).getTime() + '+0800)/';
                    //var val = '/Date(' + new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]).getTime() + ')/';
                    this[key] = val;
                    return val;
                }
            }
            return value;
        });
    };
    JSON.dateStringToDate = function (dtString) {
        /// <summary>
        /// Converts a JSON ISO or MSAJAX string into a date object
        /// </summary>
        /// <param name="" type="var">Date String</param>
        /// <returns type="date or null if invalid" />
        var a = reISO.exec(dtString);
        if (a)
            return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
        a = reMsAjax.exec(dtString);
        if (a) {
            var b = a[1].split(/[-,.]/);
            return new Date(+b[0]);
        }
        return null;
    };
}
//#endregion

//#region autoComplete
var autoComplete = function () { }
autoComplete.prototype = {
    self: null,//当前对象
    dataCallback:null,
    binder: null,
    destroy:false,
    itemEventBack: null,
};
autoComplete.prototype.init = function () {
    this.self.ldid = $.uniqueId();//生成唯一的id
    this.self.attr("commonbox-id", this.self.ldid);
    this.self.value = this.self.attr("data");//当前值
    this.self.fa = this.self.attr("fa");//fa 是标识是否有文本框后边的按钮，对应的值是按钮的样式
    this.self.$ul = null;

    this.self.wrap("<div class='relative inline-block all t-l'></div>");

    this.fa();
    this.action();
    var m = this;
    var self = m.self;
    $(document).bind("click." + self.ldid, function (e) {
        if (self.$ul && $(e.target).not(self).not(self.next("a[mark]")).size()>0) {
            m.hide();
        }
    });
};
autoComplete.prototype.fa = function () {
    if (this.self.fa) {
        this.self.after("<a href=\"javascript: void(0)\" class=\"l-btn fa absolute " + this.self.fa + " block c5 btn-hg6\" mark=\"" + this.self.fa + "\"></a>");
    }
};
autoComplete.prototype.hide = function () {
    this.self.$ul.hide();
    this.self.removeClass("select");
    this.self.next("a[mark]").removeClass("fa-angle-up").addClass("fa-angle-down");
};
autoComplete.prototype.actionCheck = function () {
    var $ul = this.self.$ul;
    if (this.destroy && $ul) {
        if ($ul.is(":visible")) {
            $ul.remove();
            this.self.next("a[mark]").removeClass("fa-angle-up").addClass("fa-angle-down");
            $ul = null;
            return false;
        } else {
            $ul.remove();
            $ul = null;
        }
    }

    if ($ul) {
        if ($ul.is(":visible")) {
            this.hide();
        } else {
            this.self.next("a[mark]").removeClass("fa-angle-down").removeClass("l-loading").addClass("fa-angle-up");
            $ul.show();
        }
        return false;
    } else {
        if (this.self.parent().find(".l-loading").size() > 0) {//当正在加载（防止不停的请求）
            return false;
        }
    }
    return true;
};
autoComplete.prototype.action = function () {};
autoComplete.prototype.generate = function (data,obj) {
    var html = [];
    obj.self.value = obj.self.attr("data");//当前值
    html.push('<ul class="l-commonbox absolute" id="' + obj.self.ldid + '">');
    for (var i = 0; i < data.length; i++) {
        obj.itemTemplate(data[i],html)
    }
    html.push('<ul>');
    obj.self.$ul = $(html.join("")).appendTo($("body"));
    obj.position();
    obj.itemEvent();
    obj.self.next("a[mark]").removeClass("fa-angle-down").removeClass("l-loading").addClass("fa-angle-up");
}
//生成列表选项
autoComplete.prototype.itemTemplate = function (item,html) {
    var value = item[this.binder.value];
    var text = item[this.binder.text];
    var c = "";
    if (value == this.self.value) {
        c="class=\"cur\""
    }
    html.push("<li ")
    html.push(c);
    html.push(" data=\"" + value + "\" ");
    for (var k in item) {
        html.push(" "+k + "=" + item[k]+" ");
    }
    html.push(">");
    html.push(text);
    html.push("</li>");
};
//计算位置
autoComplete.prototype.position = function () {
    //计算位置
    var top = this.self.offset().top + this.self.outerHeight() - 1;
    var $ul = this.self.$ul;
    if (top + $ul.outerHeight() > ($(window).height() + $(window).scrollTop())) {
        top = this.self.offset().top - $ul.outerHeight() + 1;
    }
    $ul.css({
        "left": this.self.offset().left + "px",
        "top": top + "px",
        "width": (this.self.outerWidth() - 2) + "px"
    });
};
autoComplete.prototype.itemEvent = function () {
    var m = this;
    var index = -1;//当前li
    var lisize = m.self.$ul.find("li").size();

    m.self.$ul.on("click", "li", function () {
        var $this = $(this);
        m.self.$ul.find("li").removeClass("cur");
        $this.addClass("cur");
        m.self.val($this.html()).attr("data", $this.attr("data")).focus();
        m.itemEventBack && m.itemEventBack($this,m.self);
    });
    m.self.bind("keydown", function (event) {
        var $this = $(this);
        var key = event.keyCode;
        if (!(key == 13 || key == 38 || key == 40)) {
            return;
        }
        if (key == 13) {
            var $cur = m.self.$ul.find("li.cur");
            m.self.val($cur.html()).attr("data", $cur.attr("data")).focus();
            m.itemEventBack && m.itemEventBack($cur,$this);
            m.self.$ul.hide();
            return;
        }
        if (!m.self.$ul.is(":visible")) {
            return;
        }
        if (key == 38) { /*向上按钮*/
            index--;
            if (index < 0) {
                index = lisize; //到顶了，   
            }
        } else if (key == 40) {/*向下按钮*/
            index++;
            if (index > lisize) {
                index = 1; //到底了   
            }
        }
        if (key == 38 || key == 40) {
            var $li = m.self.$ul.find("li:eq(" + index + ")");
            m.self.$ul.find("li").removeClass("cur");
            $li.addClass("cur");
            m.self.val($li.html());
        }
    });
};

$.fn.autocomplete = function (options) {
    var self = $(this);
    var defaults = {
        url: "",
        data: null,
        dataType: "",
        type: "",
        binder: { text: "text", value: "value" },
        itemEvent: null,
        callback: null
    };
    $.extend(defaults, options);
    var autocomplete = new autoComplete();
    autocomplete.self = self;
    autocomplete.destroy = true;
    autocomplete.binder = defaults.binder;
    autocomplete.itemEventBack = defaults.itemEvent;
    autocomplete.action = function () {
        var m = this;
        var $ul = this.self.$ul;
        m.self.bind("keyup", function (ev) {
            var key = ev.keyCode;
            if (key == 13 || key == 38 || key == 40) {
                return;
            }
            if (m.actionCheck()) {
                if (!$.trim($(this).val())) return;
                var params = { key: $(this).val() };
                if (!$ul && m.dataCallback(params,m.generate, m)) {
                    //样式
                    m.self.addClass("select");
                    $(".l-commonbox").not("#" + m.self.ldid).hide();
                    $("input[commonbox-id]").not("input[commonbox-id=" + m.self.ldid + "]").each(function () {
                        $(this).removeClass("select");
                        $(this).next("a[mark]").removeClass("fa-angle-up").removeClass("l-loading").addClass("fa-angle-down");
                    });
                    $.stopPropagation(ev);
                }
            }
        });
    };
    autocomplete.dataCallback = function (params,callback, obj) {
        $.lajax({
            url: defaults.url,
            dataType: defaults.dataType,
            params:params,
            type: defaults.type,
            callback: function (ret) {
                callback && callback(ret, obj);
            }
        });
        return true;
    };
    autocomplete.init();
};
//#endregion

//#region commonbox
$.fn.commonboxBase = function (options) {
    var self = $(this);
    var defaults = {
        data: null,
        binder: { text: "text", value: "value" },
        reaset: false,
        itemEvent: null,//点击下拉选项
        destroy: false,//关闭是否销毁
        callback: null
    };
    $.extend(defaults, options);
    var commonbox = new autoComplete();
    commonbox.self = self;
    commonbox.action = function () {
        var m = this;
        var $ul = this.self.$ul;
        m.self.parent().on("click", "a[mark],input", function (ev) {
            m.self.focus();
            if (m.actionCheck()) {
                if (!m.self.$ul && m.dataCallback(m.generate, m)) {
                    //样式
                    m.self.addClass("select");
                    $(".l-commonbox").not("#" + m.self.ldid).hide();
                    $("input[commonbox-id]").not("input[commonbox-id=" + m.self.ldid + "]").each(function () {
                        $(this).removeClass("select");
                        $(this).next("a[mark]").removeClass("fa-angle-up").removeClass("l-loading").addClass("fa-angle-down");
                    });
                    $.stopPropagation(ev);
                }
            }
        });
    };
    commonbox.self.css({ "width": (commonbox.self.width() - 42) + "px" });
    commonbox.binder = defaults.binder;
    commonbox.dataCallback = defaults.data;
    commonbox.itemEventBack = defaults.itemEvent;
    commonbox.init();
};
$.fn.commonbox = function (options) {
    var self = $(this);
    var defaults = {
        url: "",
        data: null,
        dataType: "",
        type: "",
        binder: { text: "text", value: "value" },
        itemEvent: null,
        callback: null
    };
    $.extend(defaults, options);
    var commonbox = new autoComplete();
    commonbox.action = function () {
        var m = this;
        var $ul = this.self.$ul;
        m.self.parent().on("click", "a[mark],input", function (ev) {
            m.self.focus();
            if (m.actionCheck()) {
                if (!m.self.$ul && m.dataCallback(m.generate,m)) {
                    //样式
                    m.self.addClass("select");
                    $(".l-commonbox").not("#" + m.self.ldid).hide();
                    $("input[commonbox-id]").not("input[commonbox-id=" + m.self.ldid + "]").each(function () {
                        $(this).removeClass("select");
                        $(this).next("a[mark]").removeClass("fa-angle-up").removeClass("l-loading").addClass("fa-angle-down");
                    });
                    $.stopPropagation(ev);
                }
            }
        });
    };
    commonbox.self = self;
    if (!commonbox.self.hasClass("full")){
        commonbox.self.css({ "width": (commonbox.self.width() - 42) + "px" });
    }
    commonbox.binder = defaults.binder;
    commonbox.itemEventBack = defaults.itemEvent;
    commonbox.dataCallback = function (callback,obj) {
        if (!defaults.url && defaults.data) {
            callback && callback(defaults.data,obj);
            return true;
        }
        commonbox.self.next("a[mark]").removeClass("fa-angle-down").addClass("l-loading");
        $.lajax({
            url: defaults.url,
            dataType: defaults.dataType,
            type:defaults.type,
            callback: function (ret) {
                callback && callback(ret,obj);
            }
        });
        return true;
    }
    commonbox.init();
}
//#endregion

//#region Area
$.extend({
    area: function(options) {
        var defaults = {
            name:"AreaId",
        };
        $.extend(defaults, options);

        $.lajax({
            url: "/script/ld-area.json",
            dataType: "json",
            type: "get",
            callback: function (ret) {
                
                var areas = {};
                var areadatas = [];
                //#region 解析数据
                for (var i = 0; i < ret.length; i++) {
                    var id = ret[i]["id"];
                    var areaCode = ret[i]["areaCode"];
                    var province = ret[i]["province"];
                    var city = ret[i]["city"];
                    var district = ret[i]["district"];
                    var detail = ret[i]["detail"];
                    if (!areas[province]) {
                        areas[province] = {
                            province: province,
                            items: {},
                            itemlists:[]
                        };
                        areadatas.push(areas[province]);
                    }
                    if (city && !areas[province].items[city]) {
                        areas[province].items[city] = {
                            city: city,
                            items: {},
                            itemlists:[]
                        };
                        areas[province].itemlists.push(areas[province].items[city]);
                    }
                    if (district && !areas[province].items[city].items[district]) {
                        areas[province].items[city].items[district] = {
                            id: id,
                            district: district,
                            areaCode: areaCode,
                            detail:detail
                        };
                        areas[province].items[city].itemlists.push(areas[province].items[city].items[district]);
                    }
                }
                //#endregion
                var $province = $("#"+defaults.name+"_Province");
                var $city = $("#"+defaults.name+"_City");
                var $area = $("#" + defaults.name + "_Area");
                var $areaId = $("#" + defaults.name);
                var areaId = $areaId.val();
                
                if (areaId) {
                    var v=ret[areaId-1];
                    $province.val(v.province).attr("data", v.province);
                    $city.val(v.city).attr("data", v.city);
                    $area.val(v.district).attr("data", v.id);
                }
                var province = $province.val();
                var city = $city.val();
                var area = $area.val();
               

                var setVal = function () {
                    $city.val(city).attr("data", city);
                    $area.val(area.district).attr("data", area.id);
                    $("#" + defaults.name).val(area.id).focusout();
                };
                $province.commonboxBase({
                    data: function(callback,obj) {
                        callback && callback(areadatas,obj);
                        return true;
                    },
                    binder: { text: "province", value: "province" },
                    itemEvent: function () {
                        province = $province.val();
                        city = areas[province].itemlists[0].city;
                        area = areas[province].items[city].itemlists[0];
                        setVal();
                    }
                });
                $city.commonboxBase({
                    data: function (callback,obj) {
                        if (!province) {
                            $.lalert("请选择省份");
                            $province.focus();
                            return false;
                        }
                        callback && callback(areas[province].itemlists,obj);
                        return true;
                    },
                    binder: { text: "city", value: "city" },
                    destroy:true,
                    itemEvent: function () {
                        city = $city.val();
                        setVal();
                    }
                });
                $area.commonboxBase({
                    data: function (callback,obj) {
                        if (!province) {
                            $.lalert("请选择省份");
                            $province.focus();
                            return false;
                        }
                        if (!city) {
                            $.lalert("请选择城市");
                            $city.focus();
                            return false;
                        }
                        callback && callback(areas[province].items[city].itemlists,obj);
                        return true;
                    },
                    binder: { text: "district", value: "id" },
                    destroy: true,
                    itemEvent: function (obj) {
                        $("#" + defaults.name).val(obj.attr("data"));
                    }
                });
            }
        });
    }
});
//#endregion

//#region 开始
var iframes = {};
$.extend({
    start: function(options) {
        var defaults = {

        };
        $.extend(defaults, options);
        iframes = {};
        var iframe = function (tag,ref) {
            var $content = $("#l-m-content");
            var $iframe= $("<iframe frameborder=\"no\" border=\"0\"  width=\"100%\" height=\"100%\" src=\"" + ref + "\" id=\"" + tag + "\"></iframe>").appendTo($content);
            $iframe.load(function () {
                var $contents = $iframe.contents();
                var $title = $contents.find("title");
                var title = $title.text();
                if(title){
                    $("#l-navtab").find("a[tag='" + tag + "']").attr("title", title).find(".l-navtab-text").html(title);
                }
                $contents.on("click", "a[ref]", function () {
                    newTabIframe($(this));
                });
                $contents.on("click", function () {
                    $(".l-start-list",window.parent.document).hide();
                    $(".l-start",window.parent.document).removeClass("cur");
                });

            });
            return $iframe;
        };
        var tab = function (tag,name) {
            var $navtab = $("#l-navtab");
            var $oldcur = $navtab.find(".cur");
            $("iframe#" + $oldcur.attr("tag")).hide();
            $oldcur.removeClass("cur");

            var $a = $("<a href=\"javascript:void(0)\" title=\""+name+"\" class=\"cur\" tag=\"" + tag + "\"><span class=\"l-navtab-text\">" + name + "</span></a>").appendTo($navtab);

            var $state = $("<span class=\"l-navtab-state\">*</span>");
            var $close = $("<span class=\"l-navtab-close\">×</span>").appendTo($a);
            $close.bind("click", function() {
                $("iframe#" + tag).remove();
                $a.remove();
                iframes[tag] = null;
                delete iframes[tag];
                if ($("#l-navtab").find(".cur").size() <= 0) {
                    if ($a.next().size() > 0) {
                        $a.next().trigger("click");
                    } else {
                        $("#l-navtab").children().last().trigger("click");
                    }
                }
                mathTab();
            });
            return $a;
        };
        var mathTab = function () {
            var $navtab = $("#l-navtab");
            var $tabs = $navtab.find("a[tag]");
            var width = $navtab.outerWidth() / $tabs.size() - 32;
            if (width < 12) {
                $tabs.find(".l-navtab-close").hide();
            }
            $tabs.css({
                width: width+"px"
            });
            $tabs.children(".l-navtab-text").css({
                width: width-4 + "px"
            });
        };
        var checkSingle = function (single, ref) {
            if (single) {
                var i = 0;
                var frame = null;
                for (var f in iframes) {
                    if (iframes[f].ref == ref) {
                        i++;
                        frame =iframes[f];
                        break;
                    }
                }
                if (i > 0) {
                    return {
                        result: true,
                        frame: frame
                    };
                }
            }
            return {
                result: false,
                frame: null
            };
        };
        var showTab = function (frame) {
            $("#l-navtab").find(".cur").removeClass("cur");
            $("#l-m-content").find("iframe").hide();
            if (frame.$tab.width() < 12) {
                $("#l-navtab").find(".l-navtab-close").hide();
            }
            frame.$tab.addClass("cur").show();
            frame.$tab.find(".l-navtab-close").show();
            frame.$iframe.show();
        };
        var newTabIframe = function ($this) {
            var ref = $this.attr("ref");
            var single = $this.attr("single");
            var singleResult = checkSingle(single, ref);
            if (singleResult.result) {
                showTab(singleResult.frame);
            } else {
                var tag = $.uniqueId();
                setTimeout(function () {
                    var $tab = new tab(tag, $this.text());
                    var $iframe = new iframe(tag, ref);
                    mathTab();
                    iframes[tag] = { $tab: $tab, $iframe: $iframe, ref: ref };
                }, 100);
            }
        };
        $("#l-navtab").on("click", "a[tag]", function () {
            var $this = $(this);
            $("#l-navtab").find(".cur").removeClass("cur");
            if ($this.width() < 12) {
                $("#l-navtab").find(".l-navtab-close").hide();
            }
            $this.addClass("cur").show();
            $this.find(".l-navtab-close").show();
            $("#l-m-content").find("iframe").hide();
            $("iframe#" + $this.attr("tag")).show();
        });

        $(".l-start").bind("click", function () {
            var $this = $(this);
            if ($this.hasClass("cur")) {
                $this.removeClass("cur");
                $(".l-start-list").hide();
            } else {
                $this.addClass("cur");
                $(".l-start-list").show();
            }
        });

        $(".l-start-list").on("click", "dd>a", function () {
            var $this = $(this);
            newTabIframe($this);
            $(".l-start-list").hide();
            $(".l-start").removeClass("cur");
        });
        $(window).resize(function() {
            mathTab();
        });
        $(document).on("click", function (ev) {
            if ($(ev.target).not(".l-start").not(".l-start-list").not(".l-m-top").size() > 0) {
                $(".l-start-list").hide();
                $(".l-start").removeClass("cur");
            }
        });
        $(window.parent).bind('beforeunload', function () { return '你的操作还未完成，确定离开此页面吗？'; });
    }
});
//#endregion

//#region Tooltip
; (function () {
    var $Tooltip = $("Tooltip");
});
//#endregion

//#region 关闭当前表单，并刷新列表
$.extend({
    closeform: function (options) {
        var defaults = {
            formUrl: "",
            listUrl:""
        };
        
        $.extend(defaults, options);
        var parent = window.parent;
        var $parent = $(parent.document);
        var $formIframe = $parent.find("iframe[src='" + defaults.formUrl + "']");
        var $listIframe = $parent.find("iframe[src='" + defaults.listUrl + "']");
        var $navtab = $parent.find("#l-navtab");

        var formIframeId = $formIframe.attr("id");
        var listIframeId = $listIframe.attr("id");
        var src = $listIframe.attr("src");

        $formIframe.remove();
        $navtab.find("a[tag=" + formIframeId + "]").remove();
        
        parent.iframes[formIframeId] == null;
        delete parent.iframes[formIframeId];

        $navtab.find("a[tag=" + listIframeId + "]").addClass("cur");
        $listIframe.show().attr("src", src);
    }
});
//#endregion

//#region 页面上的ajax post 提交
$.extend({
    ajaxpost: function () {
        $(document).on("click", "a[ajaxpost]", function () {
            var $this = $(this);
            var attributes = $(this).context.attributes;
            var params = {};
            var callback = null;
            var url = null;
            var tag = null;
            for (var i = 0, max = attributes.length; i < max; i++) {
                var nodeName = attributes[i].nodeName;
                var nodeValue = attributes[i].nodeValue;
                if (nodeName == "href" || nodeName == "ajaxpost") { continue; }
                if (nodeName == "callback") {
                    callback = nodeValue;
                    continue;
                }
                if (nodeName == "url") {
                    url = nodeValue;
                    continue;
                }
                if (nodeName == "tag") {
                    tag = nodeValue;
                }
                params[nodeName] = nodeValue;
            }
            if (tag == "delete") {
                if (!confirm("确定要执行删除操作？")) {
                    return;
                }
            }
            $.lajax({
                url: url,
                params: params,
                callback: function (ret) {
                    callback && window["$"][callback]($this,ret);
                }
            });
        });
    },
    //删除数据后，删除一行tr
    callbackRemoveTr: function ($this, data) {
        if (!data.ret) {
            data.message && $.lalert(data.message);
            return;
        } else {
           data.message && $.lalert(data.message);
           $this.parents("tr").remove();
        }
    }
});
$(function () {
    $.ajaxpost();
});
//#endregion

//#region table
$.fn.editetable = function (options) {
    var self = $(this);
    var defaults = {
        NewTr: {allow:false,template:null,callback:null},
        DeleteTr: { allow: false, callback: null },
        FixedHead: {
            width: "100%",
            height:"auto",
        }
    };
    var id = self.attr("id");

    for (var key in defaults) {
        var $tag = $("tablefor[for="+id+"]").find(key);
        if ($tag.size() > 0) {
            for (var item in defaults[key]) {
                defaults[key][item] = $tag.attr(item);
            }
        }
    }

    $.extend(defaults, options);

    self.on("keydown", "tr input:text", function (event) {
        var $input = $(this);
        var commonboxid = $input.attr("commonbox-id");
        if (commonboxid) {
            if ($("#" + commonboxid).is(":visible")) {
                return;
            }
        }

        var $curTr = $input.closest("tr");
        var $prvTr = $input.closest("tr").prev("tr");
        var $nextTr = $input.closest("tr").next("tr");

        var $td = $input.closest("td");
        var $tds = $input.closest("tr").find("td");

        var coluncount = $tds.size();
        var colun = $tds.index($td);

        var key = event.keyCode;
        if (key == 38) {//上
            $prvTr.find("td:eq(" + colun + ")").find("input:text").focus();
        }
        if (key == 40) {//下
            $nextTr.find("td:eq(" + colun + ")").find("input:text").focus();
        }
        if (key == 37) {//左
            for (var i = colun - 1; i >= 0; i--) {
                var $f = $curTr.find("td:eq(" + i + ")").find("input:text");
                if ($f.size() > 0) {
                    $f.focus();
                    return;
                }

            }
        }
        if (key == 39) {//右
            for (var i = colun + 1; i <= coluncount; i++) {
                var $f = $curTr.find("td:eq(" + i + ")").find("input:text");
                if ($f.size() > 0) {
                    $f.focus();
                    return;
                }
            }
        }
    });
    
    if (defaults.NewTr.allow) {
        self.on("focusin", "tr:last input:text", function () {
            var $this = $(this);

            if (self.find(".form-edit-error").size() > 0) {
                return;
            }
            self.find("input:text").each(function () {
                var $s=$(this);
                if (!$s.input().data("result") || !$s.input().data("result").result) {
                   $s.input().doVerification();
                }
            });
            if (self.find(".form-edit-error").size() > 0) {
                return;
            }
            var $tr = $this.parents("tr");
            var index = parseInt($tr.attr("index"));
            $tr.after(defaults.NewTr.template(index+1));
            defaults.NewTr.callback && defaults.NewTr.callback($tr.next("tr"));
        });
    }
    if (defaults.DeleteTr.allow) {
        self.on("click", "a[mark=del]",function () {
            $(this).parents("tr").remove();
            defaults.DeleteTr.callback && defaults.DeleteTr.callback();
        });
    }
    
};
$(function () {
    $("table[mark=LedinghuoTable]").editetable();
});
//#endregion